package com.wangzhen.spring.ioc.lifecycle.initializing;

import com.wangzhen.spring.ioc.dependcy.entity.SuperUser;
import com.wangzhen.spring.ioc.dependcy.entity.Terminate;
import com.wangzhen.spring.ioc.dependcy.entity.User;
import com.wangzhen.spring.ioc.lifecycle.instantiation.InstantiationAwareBeanPostProcessorDemo;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.CommonAnnotationBeanPostProcessor;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * 演示bean对象实现
 *  BeanPostProcessor接口
 *  InitializingBean接口，
 *  SmartInitializingSingleton接口
 * 中的各个方法的调用时机
 */
public class InitializingLifeCycleDemo {

    public static void main(String[] args) {
        // 方式一：
        DefaultListableBeanFactory context = new DefaultListableBeanFactory();
        // 增加自定义的beanPostProcessor,
        context.addBeanPostProcessor(new MyBeanPostProcessor());
        // 增加spring 内部的beanPostProcessor
        context.addBeanPostProcessor(new CommonAnnotationBeanPostProcessor());
        // 增加自定义的销毁bean前执行的beanPostProcessor
        context.addBeanPostProcessor(new MyDestructionAwareBeanPostProcessorDemo());

        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(context);
        reader.loadBeanDefinitions("classpath:/META-INF/Initializing-context.xml");
        // 需要手动执行才能触发此声明周期 #
        context.preInstantiateSingletons();
        Terminate terminate = context.getBean(Terminate.class);
        // 只有执行destoryBean方法才会触发DestructionAwareBeanPostProcessor#postProcessBeforeDestruction
        context.destroyBean("terminate", terminate);


/*
        // 方法二：使用XML的应用上下文，这种方式没有调试成功
        ClassPathXmlApplicationContext context1 = new ClassPathXmlApplicationContext(new String[] {"classpath:/META-INF/Initializing-context.xml"}, false);
        context1.getBeanFactory().addBeanPostProcessor(new MyBeanPostProcessor());
        context1.refresh();
        context1.getBean(Terminate.class);*/
/*
        // 方式三：注解驱动上下文
        AnnotationConfigApplicationContext configApplicationContext = new AnnotationConfigApplicationContext();
        // 加载xml资源
        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(configApplicationContext);
        reader.loadBeanDefinitions("classpath:/META-INF/Initializing-context.xml");
        // 将当前类当做配置类注册
        configApplicationContext.register(InitializingDemo.class);
        // 加载自定义beanPostProcessor
        configApplicationContext.getBeanFactory().addBeanPostProcessor(new MyBeanPostProcessor());
        // 启动应用上下文
        configApplicationContext.refresh();

        configApplicationContext.getBean(Terminate.class);

        configApplicationContext.close();*/

    }
}
